import { WebSocket, WebSocketServer } from 'ws';
import { Connection } from './connection/Connection';


/**
 * 启动服务器
 */
export abstract class Server<T extends Connection> {
    protected _wss: WebSocketServer | null = null;
    protected _connections: T[] = [];

    get connections() {
        return this._connections;
    }

    /**
     * 启动服务器
     * @param port 
     */
    startServer(port: number) {
        this._wss = new WebSocketServer({ port });
        this._wss.on('connection', (ws: WebSocket) => {
            console.log(this.constructor.name + ' connection established');
            this.onconnect(ws)
        });
        console.log(`创建server:${port}成功`)
    }

    /**
     * 有连接进来
     * @param ws 
     */
    abstract onconnect(ws: WebSocket): void;

    /**
     * 删除连接
     * @param connection 
     */
    removeConnection(connection: T) {
        let index = this._connections.indexOf(connection);
        if (index != -1)
            this._connections.splice(index, 1);
    }
}
